<template>
  <el-container>
    <el-dialog
      :title="isAdd ? '工作类别添加' : '工作类别编辑'"
      :visible.sync="centerDialogVisible"
      @closed="closeDialog()"
      width="30%"
      center
    >
      <el-form
        ref="jobCategoryForm"
        :model="jobCategoryForm"
        label-width="100px"
        fullscreenLoading
        :rules="jobCategoryFormRules"
      >
        <el-form-item label="职位名称" prop="name">
          <el-input
            v-model="jobCategoryForm.name"
            placeholder="请输入职位名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属类别" prop="category">
          <el-select v-model="pid" style="width: 100%" placeholder="请选择类别">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm('jobCategoryForm')"
            v-loading.fullscreen.lock="fullscreenLoading"
            >确认</el-button
          >
          <el-button @click="resetForm('jobCategoryForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-container>
      <el-main>
        <el-row class="function-button">
          <el-button type="primary" size="small" round @click="handleAdd()"
            >新增按钮</el-button
          >
          <el-button type="success" size="small" round @click="refresh()"
            >刷新按钮</el-button
          >
          <el-input
            style="width: 20%; margin-left: 40px"
            placeholder="输入工作名称"
            size="samll"
            prefix-icon="el-icon-search"
            v-model="jobCategoryName"
          >
          </el-input>
          <el-select
            v-model="jobCategoryPid"
            placeholder="请选择类别"
            allow-create
            filterable
            clearable
            style="margin-left: 30px"
          >
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button round style="margin-left: 10px" @click="queryByCondition"
            >查询</el-button
          >
        </el-row>
        <template>
          <el-table
            ref="jobCategorycategoryTable"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            v-loading="loading"
            :data="jobCategorys"
            fit
            max-height="700"
            size="medium "
            class="tableStyle"
            highlight-current-row
            row-key="id"
            tooltip-effect="dark"
          >
            <el-table-column prop="id" label="工作类别编号"> </el-table-column>
            <el-table-column prop="name" label="职位名称"> </el-table-column>
            <el-table-column prop="pname" label="所属类别"></el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click.stop="handEdit(scope.row)"
                  size="small"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click.stop="handDel(scope.row)"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import throttle from 'lodash/throttle'; //
import { mapGetters } from 'vuex';
import { Message } from 'element-ui';
export default {
  name: 'JobCategoryMng',
  data() {
    var validateNameIsRepeat = async (rule, value, callback) => {
      if (!value) {
        return callback([new Error('名称不能为空')]);
      }
      // 发送请求，判断名称是重复
      let result = await this.$store.dispatch(
        'JobCategoryMng/checkIsRepeatForJobCategoryName',
        value
      );
      if (!result.data.flag) {
        if (!this.isAdd) {
          return callback('名称无变化');
        }
      }
      return result.data.flag
        ? callback()
        : callback([new Error(result.message)]);
    };
    return {
      search: '', // 前端模糊查询公司名称
      isAdd: false, // 模态窗口状态标识
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      centerDialogVisible: false, // 模态窗口启用开关
      fullscreenLoading: false,
      jobCategoryForm: {}, // 职位类别添加/修改表单
      jobCategorys: [],
      pid: 1000, // 表单校验
      jobCategoryName: '', // 查询条件
      jobCategoryPid: undefined, // 查询条件  // 默认值 计算机开发/应用类
      categoryList: [],
      jobCategoryFormRules: {
        name: [
          {
            required: true,
            validator: validateNameIsRepeat,
            trigger: 'blur',
          },
        ],
      },
    };
  },
  computed: {
    // 工作分类
    ...mapGetters('JobCategoryMng', [
      'jobCategoryIPage',
      'jobCategoryList',
      'categories',
    ]),
  },
  watch: {
    categories() {
      this.$set(this, 'categoryList', this.categories);
    },
    jobCategoryList() {
      this.$set(this, 'jobCategorys', this.jobCategoryList);
      this.loading = false;
    },
    jobCategoryIPage() {
      if (this.jobCategoryIPage.currentPage) {
        this.currentPage = this.jobCategoryIPage.currentPage;
      }
      if (this.jobCategoryIPage.pageSize) {
        this.pageSize = this.jobCategoryIPage.pageSize;
      }
      if (this.jobCategoryIPage.total) {
        this.total = this.jobCategoryIPage.total;
      }
    },
  },
  mounted() {
    this.getJobCategoryList();
    this.getCategories();
  },
  methods: {
    // 获取工作大类别集合
    getCategories() {
      this.$store.dispatch('JobCategoryMng/getCategories');
    },

    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.getJobCategoryList();
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getJobCategoryList();
    },

    // 查询职位类别信息
    getJobCategoryList() {
      this.loading = true;
      let params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        condition: this.condition || {},
      };
      this.$store.dispatch('JobCategoryMng/getJobCategoryList', params);
    },
    // 删除职位类别
    handDel(row) {
      let result;
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      })
        .then(async () => {
          result = await this.$store.dispatch('JobCategoryMng/delJobCategory', [
            row.id,
          ]);
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
          this.getJobCategoryList();
        })
        .catch(() => {
          this.$message({
            message: '取消删除',
            type: 'info',
            duration: 2 * 1000,
          });
        });
    },
    // 刷新企业列表
    refresh: throttle(async function () {
      this.currentPage = 1;
      await this.getJobCategoryList();
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 1 * 1000,
      });
    }, 800),
    // 新增职位类别
    handleAdd() {
      this.jobCategoryForm = {};
      if (this.$refs.jobCategoryForm) {
        this.resetForm('jobCategoryForm');
      }
      this.isAdd = true;
      this.centerDialogVisible = true;
    },
    // 编辑职位类别
    handEdit(row) {
      if (this.$refs.jobCategoryForm) {
        this.resetForm('jobCategoryForm');
      }
      this.jobCategoryForm = row;
      this.centerDialogVisible = true;
    },
    // 重置表单判定状态
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 对话框关闭前的回调
    closeDialog() {
      this.isAdd = false;
    },
    // 城市选择
    handleChange(type) {
      var loc = '';
      if (type == 'job') {
        for (let i = 0; i < this.selectedJob.length; i++) {
          // this.$refs["cascader"].getCheckedNodes()[0].label 获取选中的label
          loc += this.$refs['cascader'].getCheckedNodes()[0].label;
        }
      } else {
        for (let i = 0; i < this.selectedProvince.length; i++) {
          loc += CodeToText[this.selectedProvince[i]];
        }
      }
      alert(loc);
    },

    // 条件查询
    async queryByCondition() {
      // 初始化条件查询参数
      this.condition = {};
      if (this.jobCategoryName) {
        this.condition.name = this.jobCategoryName;
      }
      if (this.jobCategoryPid) {
        this.condition.pid = this.jobCategoryPid;
      }
      await this.getJobCategoryList();
      this.$nextTick(() => {
        this.$message({
          message: '查询成功',
          type: 'success',
          duration: 1 * 1000,
        });
      });
    },

    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.fullscreenLoading = true;
          try {
            // 接收返回的结果
            let result = {};
            if (this.isAdd) {
              let paramsArray = [];
              this.jobCategoryForm.pid = this.pid;
              let params = {
                ...this.jobCategoryForm,
              };
              paramsArray.push(params);
              // 发送请求
              result = await this.$store.dispatch(
                'JobCategoryMng/batchAddJobCategory',
                paramsArray
              );
            } else {
              result = await this.$store.dispatch(
                'JobCategoryMng/editJobCategory',
                this.jobCategoryForm
              );
            }
            // 执行成功返回结果，
            // 更新专业列表
            this.getJobCategoryList();
            this.$message({
              message: result.message,
              type: 'success',
              duration: 2 * 1000,
            });
          } catch (error) {
            Message.error(error || 'Has Error');
          } finally {
            this.fullscreenLoading = false; // 关闭遮罩层
            this.isAdd = false; // 重置表单状态
            this.centerDialogVisible = false; // 关闭模态窗口
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
// 分页插件居中对齐
.block {
  text-align: center;
}
</style>
